package com.ikas.ai.server.module.morningpaper.service;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ikas.ai.server.module.morningpaper.consts.MorningPaperFailRecordVariableNames;
import com.ikas.ai.server.module.morningpaper.model.dto.MorningPaperFailRecordsDto;
import com.ikas.ai.server.module.morningpaper.model.po.MorningPaperVariablesPo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author li.hexian
 * 执行失败记录相关接口及工具
 */
@Service
public class MorningPaperFailRecordService {

    @Autowired
    MorningPaperVariablesService morningPaperVariablesService;

    /**
     * 获取全年工况执行失败记录
     * @return
     */
    public MorningPaperFailRecordsDto get(){
        Map<String, String> variablesMap = morningPaperVariablesService.list(
                new LambdaQueryWrapper<MorningPaperVariablesPo>()
                        .in(
                                MorningPaperVariablesPo::getVariableName,
                                Arrays.stream(MorningPaperFailRecordVariableNames.values())
                                        .map(bean -> bean.name())
                                        .collect(Collectors.toList())
                        )
        ).stream().collect(
                Collectors.toMap(
                        MorningPaperVariablesPo::getVariableName,
                        MorningPaperVariablesPo::getValue)
        );

        return BeanUtil.mapToBean(variablesMap, MorningPaperFailRecordsDto.class, null);
    }

    /**
     * 更新执行失败记录，改动表：t_morning_paper_variables
     * @param mfv
     * @param posMap
     */
    @Transactional
    public void refresh(MorningPaperFailRecordsDto mfv,Map<String,MorningPaperVariablesPo> posMap){
        Map<String, Object> failRecordMap = BeanUtil.beanToMap(mfv);
        morningPaperVariablesService.updateBatchById(
                morningPaperVariablesService.fillPoList(failRecordMap, posMap)
        );
    }

}
